package cn.micai.base.concurrent;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 描述：使用copy-on-write 集合和一般类型集合进行遍历的例子：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/14 14:53
 */
public class CopyOnWriteDemo {

    public static void main(String [] args) {
        String [] ss = {"aa", "bb", "cc"};
        List list1 = new CopyOnWriteArrayList<>(Arrays.asList(ss));
        List list2 = new ArrayList(Arrays.asList(ss));
        Iterator iterator1 = list1.iterator();
        Iterator iterator2 = list2.iterator();
        list1.add("New");
        list2.add("New");
        try {
            printAll(iterator1);
        } catch (ConcurrentModificationException e) {
            System.out.println("Shouldn't get here");
        }
        try {
            printAll(iterator2);
        } catch (ConcurrentModificationException e) {
            System.err.println("Will get here.ConcurrentModificationException occurs!");
        }
    }

    private static void printAll(Iterator iterator) {
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
